<template>
	<view class="">
		<view class="button-material" v-if="!disEdit()">
			<button type="primary" @click="selectMaterial">{{$t('baseCommon.buttons.add', { title: $t('equipment.common.spareParts') })}}</button>
			<button type="primary" @click="cerateCollar">{{$t('ticket.buttons.cerateCollar')}}</button>
			<button type="primary" @click="cerateReturn">{{$t('ticket.buttons.cerateReturn')}}</button>
		</view>
		<scroll-view scroll-y="true" :class="isView ? '' : disEdit() ? 'scroll-height-edit' : 'scroll-height'">
			<view v-for="(item, index) in listData" :key="index">
				<uni-swipe-action>
					<uni-swipe-action-item :right-options="options" :disabled="disEdit()" @click="delItem(item, index)">
						<view class="index">
							<view class="idx">{{index + 1}}</view>
						</view>
						<view class="condition">
							<view class="conmenus" v-if="!disEdit()">
								<view class="conleft">{{$t('common.buttons.choice')}}</view>
								<view class="conright" style="text-align: left;">
									<checkbox style="transform: scale(0.7);" :checked="item.checked" @click="checkItem(item, index)"></checkbox>
								</view>
							</view>
							<view class="contexts">
								<view class="conleft">{{$t('material.itemDesc')}}</view>
								<view class="contextright">{{item.materialDesc}}</view>
							</view>
							<view class="conmenus">
								<view class="conleft">{{$t('material.stockQuantity')}}</view>
								<view class="conright">{{item.availableQty}}</view>
							</view>
							<view class="conmenus">
								<view class="conleft">{{$t('material.planQuantity')}}</view>
								<view class="conright">
									<input v-model="item.planQty" type="number" :placeholder="$t('baseCommon.message.pleaseEnter', { title: '' })" :disabled="disEdit()" @input="checkQty(item)"/>
								</view>
							</view>
							<view class="conmenus" v-if="item.collectionQty">
								<view class="conleft">{{$t('material.collarOrder.collarQuantity')}}</view>
								<view class="conright">{{item.collectionQty}}</view>
							</view>
							<view class="conmenus" v-if="item.actualQty">
								<view class="conleft">{{$t('material.actualQuantity')}}</view>
								<view class="conright">{{item.actualQty}}</view>
							</view>
						</view>
					</uni-swipe-action-item>
				</uni-swipe-action>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import { saveDataMaterialsApi, addConectInfoApi, updateDataMaterialsApi, deleteSingleMaterialsApi, updateSingleMaterialsApi } from '@/api/business/workorder.js'
	import { notice, business } from '@/utils/common.js'
	
	export default {
		props: {
			form: {
				type: Object,
				default() {
					return {}
				}
			},
			data: {
				type: Array,
				default() {
					return []
				}
			},
			editData: {
				type: Array,
				default() {
					return []
				}
			},
			isView: {
				type: Boolean
			}
		},
		data() {
			return {
				options: [{
					text: this.$t('baseCommon.buttons.delete'),
					style: {
						backgroundColor: '#dd524d'
					}
				}],
				listData: [],
				checkedList: []
			}
		},
		computed: {
			pageCollar() {
				return business.getPagePath('m_mat_pick_create')
			},
			pageReturn() {
				return business.getPagePath('m_mat_return_create')
			},
		},
		mounted() {
			this.init()
		},
		methods: {
			init() {
				this.listData = this.data
			},
			/**
			 * 禁用编辑
			 */
			disEdit() {
				return !this.editData.includes("app_material")
			},
			selectMaterial() {
				let checkes = []
				this.listData.forEach(item=>{
					checkes.push(item.stockId)
				})
				let that = this
				uni.navigateTo({
					url: '/pages/business/defect/select-material?siteId=' + that.form.operationTeamNo + '&checkes=' + checkes.join(),
					events: {
						selectMaterial(data) {
							for (const index in data) {
								const row = {
									actualAmt: '', // 实际金额
									actualQty: '', // 实际数量
									availableQty: data[index].availableQuantity, // 可用数量
									// collarId: '',
									collectionQty: '', // 领用数量
									depository: data[index].slName, // 仓库
									depositoryId: data[index].slId, // 仓库ID
									gmlId: '',
									manufacturer: data[index].winningSupplierName, // 生产厂商
									materialDesc: data[index].itemDesc, // 物资描述
									materialName: data[index].itemName, // 物资名称
									materialNo: data[index].itemNo, // 物资编码
									memo: '',
									partOrMaterial: '', // 类型
									planAmt: '', // 计划金额
									planQty: '', // 计划数量
									planTime: '', // 需求日期
									// returnId: '',
									sortNo: 0, // 序号
									state: false, // 状态
									stockId: data[index].stockId,
									unit: data[index].item.baseUnit, // 单位
									unitCost: data[index].price, // 成本单价
									woId: '', // 工单id
								}
								row.woId = that.form.woId
								let hasSame = false
								that.listData.forEach((item) => {
									if (item.stockId == row.stockId) {
										hasSame = true
									}
								})
								if (!hasSame) {
									that.listData.push(row)
								}
							}
							// 保存物资信息
							saveDataMaterialsApi(that.listData).then(res=>{
								that.$emit("resetData", res.data)
								that.$set(that, "listData", JSON.parse(JSON.stringify(res.data)))
							})
						}
					}
				})
			},
			checkQty(item) {
				if(parseInt(item.planQty) > parseInt(item.availableQty)) {
					notice.toast(this.$t('material.message.cannotGreater', { title1: this.$t('material.planQuantity'), title2: this.$t('material.stockQuantity')}))
					item.planQty = 0
					return
				}
				item.planAmt = parseFloat(item.unitCost * item.planQty).toFixed(2)
				updateSingleMaterialsApi(item)
				this.$emit("resetData", this.listData)
			},
			cerateCollar() {
				this.getCheckedList()
				if (this.checkedList.length === 0) {
					notice.toast(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('material.moveOrder.materialDetail')}))
					return
				}
				
				let flag = true
				// 同一个物资只能领用一次
				for(let i=0; i<this.checkedList.length; i++) {
					if(this.checkedList[i].collarId) {
						notice.toast(this.$t('material.message.collarCreated', { title: this.checkedList[i].materialName }))
						flag = false
						break
					}
				}
				// 校验物资是否属于同一个仓库
				let isSame = this.checkedList.every(item => item.depositoryId === this.checkedList[0].depositoryId)
				if(!isSame) {
					notice.toast(this.$t('material.message.selectSameWarehouse'))
					flag = false
				}
				if(!flag) {
					return
				}
				
				let sourceData = this.buildCreateParams("collar")
				let that = this
				uni.navigateTo({
					url: this.pageCollar.pageUrl + "?source=defect&sourceData=" + JSON.stringify(sourceData),
					events: {
						async cerateCollar(data) {
							that.checkedList.forEach(item=>{
								item.collarId = data.collarId
								data.collarItemList.forEach(material=>{
									if(item.stockId === material.stockId) {
										item.collarItemId = material.collarItemId
									}
								})
							})
							// 更新物资信息
							await updateDataMaterialsApi(that.checkedList)
							// 保存关联信息
							await addConectInfoApi({
								woId: that.form.woId,
								boTypeNo: "ex_mat_use",
								boId: data.collarId,
								boNo: data.collarNo,
								boContent:data.collarDesc
							})
							that.$emit("resetData", that.listData)
						}
					}
				})
			},
			cerateReturn() {
				this.getCheckedList()
				if (this.checkedList.length === 0) {
					notice.toast(this.$t('baseCommon.message.pleaseSelect', { title: this.$t('material.moveOrder.materialDetail')}))
					return
				}
				
				let flag = true
				// 同一个物资只能退用一次
				for(let i=0; i<this.checkedList.length; i++) {
					if(this.checkedList[i].returnId) {
						notice.toast(this.$t('material.message.returnCreated', { title: this.checkedList[i].materialName }))
						flag = false
						break
					}
				}
				// 校验物资是否已经领用或领用流程是否已结束
				for(let i=0; i<this.checkedList.length; i++) {
					if(!this.checkedList[i].collarId) {
						notice.toast(this.$t('material.message.collarNotCreate', { title: this.checkedList[i].materialName }))
						flag = false
						break
					}
					if(this.checkedList[i].collarId && !this.checkedList[i].collectionQty) {
						notice.toast(this.$t('material.message.collarNotFinished', { title: this.checkedList[i].materialName }))
						flag = false
						break
					}
				}
				// 校验物资是否属于同一个领料单
				let isSame = this.checkedList.every(item => item.collarId === this.checkedList[0].collarId)
				if(!isSame) {
					notice.toast(this.$t('material.message.selectSameCollar'))
					flag = false
				}
				if(!flag) {
					return
				}
				
				let sourceData = this.buildCreateParams("return")
				let that = this
				uni.navigateTo({
					url: this.pageReturn.pageUrl + "?source=defect&sourceData=" + JSON.stringify(sourceData),
					events: {
						async cerateReturn(data) {
							that.checkedList.forEach(item=>{
								item.returnId = data.returnId
								data.returnItemList.forEach(material=>{
									if(item.materialNo === material.itemNo) {
										item.returnItemId = material.returnItemId
									}
								})
							})
							// 更新物资信息
							await updateDataMaterialsApi(that.checkedList)
							// 保存关联信息
							await addConectInfoApi({
								woId: that.form.woId,
								boTypeNo: "ex_mat_gb",
								boId: data.returnId,
								boNo: data.returnNo,
								boContent:data.returnDesc
							})
							that.$emit("resetData", that.listData)
						}
					}
				})
			},
			buildCreateParams(type) {
				let stockIds = []
				let stockInfos = []
				let collarId
				let slId
				this.checkedList.forEach(item=>{
					stockIds.push(item.stockId)
					
					let stockInfo = {
						planQty: item.planQty,
						stockId: item.stockId
					}
					stockInfos.push(stockInfo)
					
					collarId = item.collarId
					slId = item.depositoryId
				})
				let params = {
					woId: this.form.woId,
					userId: this.form.mtnPersonId,
					userName: this.form.mtnPerson,
					stockIds: stockIds
				}
				if(type == "collar") { // 领用
					params.siteId = this.form.operationTeamNo
					params.dfId = this.form.dfId
					params.stockInfos = stockInfos
					params.slId = slId
				} else if(type == "return") { // 退用
					params.collarId = collarId
				}
				return params
			},
			getCheckedList() {
				this.checkedList = []
				this.listData.forEach(item=>{
					if(item.checked) {
						this.checkedList.push(item)
					}
				})
			},
			checkItem(i, index) {
				i.checked = !i.checked
				this.$set(this.listData, index, i)
			},
			delItem(item, index) {
				if (this.disEdit()) {
					return
				}
				
				// 校验物资是否已生成领料单或退料单
				if(item.collarId) {
					notice.toast(this.$t('material.message.collarCreatedNoDelete'))
					return
				}
				if(item.returnId) {
					notice.toast(this.$t('material.message.returnCreatedNoDelete'))
					return
				}
				
				deleteSingleMaterialsApi(item)
				this.listData.splice(index, 1)
				this.$emit("resetData", this.listData)
			}
		}
	}
</script>

<style lang="scss">
	@import '@/static/style/common-detail.scss';

	.scroll-height {
		padding-top: 10px;
		/* #ifdef APP-PLUS */
		height: calc(100vh - 160px);
		/* #endif*/
		/* #ifdef H5 */
		height: calc(100vh - 200px);
		/* #endif*/
	}
	
	.scroll-height-edit {
		/* #ifdef APP-PLUS */
		height: calc(100vh - 115px);
		/* #endif*/
		/* #ifdef H5 */
		height: calc(100vh - 155px);
		/* #endif*/
	}
	
	.items {
		display: flex;
	}
	
	.index {
		margin-top: 8px;
		color: #666666;
		background-color: #FFFFFF;
		width: 7%;
		text-align: center;
		display: flex;
		border-right: #e7e7e7 solid 0.5px;
		border-bottom: #e7e7e7 solid 0.5px;
	}
	
	.idx {
		width: 100%;
		transform: translate(0, calc(50% - 10px));
	}
	
	.condition {
		width: 93%;
	}
	
	.button-material {
		display: flex;

		button {
			margin: 0 5px;
			font-size: 14px;
		}

		button:nth-child(1) {
			width: 36%;
		}

		button:nth-child(2) {
			width: 32%;
		}

		button:nth-child(3) {
			width: 32%;
		}
	}
</style>
